package org.wkg.lesson08;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer_1 {

    private BlockingQueue<MyTast> queue = new PriorityBlockingQueue<>();

    public MyTimer_1() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    MyTast tast = this.queue.take();
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= tast.getTime()) {
                        tast.getRunnable().run();
                    } else {
                        queue.put(tast);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable, long delay) throws InterruptedException {
        MyTast tast = new MyTast(runnable, delay);
        queue.put(tast);
    }
}


class MyTast implements Comparable<MyTast> {
    private Runnable runnable;
    private long time;

    public MyTast(Runnable runnable, long delay) {

        if (runnable == null) {
            throw new IllegalArgumentException("输入任务不能为空");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("输入时间不能为负数");
        }

        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTast o) {
        if (this.getTime() > o.getTime()) {
            return 1;
        } else if (this.getTime() < o.getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}
